extends Node2D
class_name Sword
@onready var sword: Sprite2D = %Sword
@onready var sword_head: Node2D = %sword_head
## 挥剑轨迹
@onready var sword_line: Afterimage = %sword_line
@export var attack_time: float = 0.1
@export var attack_cool_down: float = 0.2
@export var damage = 0

var base_attack_speed = 10
## 是否正在攻击
var is_attack = false
## 是否正在挥砍
var is_rotate = false
var attack_interval = 0
var rotate_degree = 240
var time = 0
func _ready() -> void:
	## 初始下剑的方向
	## -45度是纠正向上，-30度对应240度
	sword.rotation_degrees = -75
	
func _physics_process(_delta: float) -> void:
	time += _delta
	if is_attack:
		if !is_rotate and time >= attack_interval:
			## 完成一个循环再调整攻击方向，不然有bug
			if rotate_degree == abs(rotate_degree):
				self.look_at(get_global_mouse_position())
			_rotate(rotate_degree)
			_attack()
			return
	else:
		if !is_rotate:
			## 如果间隔大于4秒不在旋转了
			if time >= 4:
				## 如果没归位，归为下
				if rotate_degree == -abs(rotate_degree):
					_rotate(rotate_degree, true)
					rotate_degree = abs(rotate_degree)
				else:
					self.look_at(get_global_mouse_position())

func _unhandled_input(event: InputEvent) -> void:
	## 获取攻击速度
	var attack_speed = Utils.get_player_stats_value("attack_speed") as int
	var additional_attack_spped = Utils.get_player_stats_value("additional_attack_speed") as int
	var total_speed = max(attack_speed + additional_attack_spped + base_attack_speed, 10)
	attack_interval =  (attack_cool_down * 100) / total_speed
	if event.is_action_pressed("shoot"):
		is_attack = true
	if event.is_action_released("shoot"):
		is_attack = false

func _rotate(angle: float, is_init: bool = false) -> void:
	is_rotate = true
	var tween = create_tween().set_parallel(false)
	tween.tween_property(sword, "rotation_degrees", sword.rotation_degrees + angle, attack_time)
	await tween.finished
	is_rotate = false
	if !is_init:
		time = 0
		rotate_degree = -rotate_degree


const sword_vfx = preload("res://scenes/entities/sword/sword_vfx.tscn")
## 生成攻击特效
func _attack():
	var sword_vfx_var = sword_vfx.instantiate()
	sword_vfx_var.get_node("%AnimationPlayer").speed_scale = sword_vfx_var.get_node("%AnimationPlayer").get_animation("attack").length / attack_time / 2 ;
	sword_vfx_var.get_node("attack_vfx").flip_v = false if get_global_mouse_position().x > global_position.x else true
	sword_vfx_var.creater = self
	sword_vfx_var.weapon_damage = 0
	self.add_child(sword_vfx_var)

